<?php
if(!function_exists("p")) {
function p($key) {
	return trim($_POST[$key]);
}
}
function pn($key) {
	return intval($_POST[$key]);
}
if(!function_exists("g")) {
function g($key) {
	return trim($_GET[$key]);
}
}
function gn($key) {
	return intval($_GET[$key]);
}
if(!function_exists("r")) {
function r($key) {
	if(isset($_REQUEST[$key])) return trim($_REQUEST[$key]);
	$info = @jd(fg("php://input"));
	if($info && isset($info[$key])) return $info[$key];
	return '';
}
}
function rn($key) {
	return intval($_REQUEST[$key]);
}
function check_dbenc() {
	global $db_enkey, $no_dbenc;
	if($no_dbenc) return ;
	if(!$db_enkey) {
		$fn = dirname(__FILE__)."/db_enkey.php";
		if(is_file($fn)) {
			require($fn);
		}
	}
}
if(!function_exists("dbenc")) {
function dbenc($s) {
	global $db_enkey;
	check_dbenc();
	if($db_enkey) {
		$s = "genc_".aes_encrypt($s, $db_enkey);
	}
	return $s;
}
}
if(!function_exists("dbdec")) {
function dbdec($s) {
	global $db_enkey;
	check_dbenc();
	if($db_enkey) {
		if(strpos($s, 'genc_') === 0) $s = substr($s, 5);
		$s = aes_decrypt($s, $db_enkey);
	}
	return $s;
}
}
function fetchOne($sql, $conn = '', $errexit = true){
	$result = query($sql, $errexit, $conn);
	if($result){
		if(gettype($result) == 'object') {
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		} else {
			$row = mysql_fetch_array($result, MYSQL_ASSOC);
		}
		if($row === false) return array();
		foreach($row as $k => $v) {
			if(strpos($v, 'genc_') === 0) {
				$row[$k] = dbdec($v);
			}
		}
		return $row;
	}else{
		return array();
	}
}

function fetchAll($sql, $conn = '', $errexit = true){
	$result=query($sql, $errexit, $conn);
	$rows = array();
	$func = "mysql_fetch_array";
	$mode = MYSQL_ASSOC;
	if(gettype($result) == 'object') {
		$func = "mysqli_fetch_array";
		$mode = MYSQLI_ASSOC;
	}
	while (@$row = $func($result, $mode)){
		foreach($row as $k => $v) {
			if(strpos($v, 'genc_') === 0) {
				$row[$k] = dbdec($v);
			}
		}
		$rows[] = $row;
	}
	return $rows;
}
function fetchCol($sql, $conn = '')
{
	$row = fetchOne($sql, $conn);
	if(!$row) return false;
	$keys = array_keys($row);
	return $row[$keys[0]];
}
if(!function_exists("query")) {
function query($sql, $errexit = true, $conn = '') {
	if(!$conn) $conn = $GLOBALS['db'];
	$is_mysqli = false;
	if($conn) {
		if(gettype($conn) == 'object') {
			$is_mysqli = true;
		}
		if($is_mysqli) {
			$rs = mysqli_query($conn, $sql);
		} else {
			$rs = mysql_query($sql, $conn);
		}
	} else $rs = mysql_query($sql);
	if($rs === false && $errexit) {
		if($GLOBALS['gyhdebug']) {
			if($is_mysqli) {
				echo $sql."\n\n".mysqli_error($conn);
			} else {
				if($conn) {
					echo $sql."\n\n".mysql_error($conn);
				} else {
					echo $sql."\n\n".mysql_error();
				}
			}
		}
		exit;
	}
	return $rs;
}
}
function fetch($rs) {
	if(gettype($rs) == 'object') {
		$row = @mysqli_fetch_array($rs, MYSQLI_ASSOC);
	} else {
		$row = @mysql_fetch_array($rs, MYSQL_ASSOC);
	}
	
	if(!$row) return false;
	foreach($row as $k => $v) {
		if(strpos($v, 'genc_') === 0) {
			$row[$k] = dbdec($v);
		}
	}
	return $row;
}
function afrows($conn = '') {
	if(!$conn) $conn = $GLOBALS['db'];
	if($conn) {
		if(gettype($conn) == 'object') {
			return mysqli_affected_rows($conn);
		} else {
			return mysql_affected_rows($conn);
		}
	} else {
		return mysql_affected_rows();
	}
}
function insert_id($conn = '') {
	if(!$conn) $conn = $GLOBALS['db'];
	if($conn) {
		if(gettype($conn) == 'object') {
			return mysqli_insert_id($conn);
		} else {
			return mysql_insert_id($conn);
		}
	} else {
		return mysql_insert_id();
	}
}

function getByPage($sql, $page = 1, $pagesize = 15, &$pageinfo = array(), $link = null)
{
	$page = max(intval($page), 1);
	$pagesize = intval($pagesize);
	if(!$pagesize) $pagesize = 15;
	if(!$link) $link = $GLOBALS['db'];
	$is_mysqli = false;
	if($link) {
		if(gettype($link) == 'object') {
			$is_mysqli = true;
			$rs = mysqli_query($link, $sql);
		} else {
			$rs = mysql_query($sql, $link);
		}
		
	} else {
		$rs = mysql_query($sql);
	}
	if(!$rs) return false;

	if($is_mysqli) {
		$numRows = mysqli_num_rows($rs);
	} else {
		$numRows = mysql_num_rows($rs);
	}

	if($numRows == 0) {
		$pageinfo['pagecount'] = 0;
		$pageinfo['count'] = 0;
		$pageinfo['page'] = 1;
		$pageinfo['pagesize'] = $pagesize;
		return array();
	}
	if($pagesize !== 0) {
		$pagesize = intval($pagesize);
		if($pagesize == "" || $pagesize < 0) $pagesize = 15;
		$pagecount = ceil($numRows / $pagesize);
		if($page == -1) $page = $pagecount;
		$page = intval($page);
		if(!$page || $page < 0) $page = 1;
		if($page > $pagecount) $page = $pagecount;

		if($is_mysqli) {
			mysqli_data_seek($rs, ($page - 1) * $pagesize);
		} else {
			mysql_data_seek($rs, ($page - 1) * $pagesize);
		}
	}
	$data = array();
	$n = 0;
	while ($row = fetch($rs)) {
		$data[] = $row;
		$n++;
		if($pagesize != 0 && $n >= $pagesize) break;
	}
	$pageinfo['pagecount'] = $pagecount;
	$pageinfo['count'] = $numRows;
	$pageinfo['page'] = $page;
	$pageinfo['pagesize'] = $pagesize;

	return $data;
}
function getByPageSql($sql, $page, $pagesize, &$pageinfo = array())
{
	if($page != -1) $page = max(intval($page), 1);
	$pagesize = max(intval($pagesize), 10);
	$sk = md5($sql);
	$cInfo = $_SESSION['sqlCountInfo'][$sk];
	if($cInfo && time() - $cInfo['time'] < 300) {
		$numRows = intval($cInfo['count']);
	} else {
		$p1 = stripos($sql, "from");
		$sqlc = "select count(*) " . substr($sql, $p1);
		$po = stripos($sqlc, "order by");
		if($po) $sqlc = substr($sqlc, 0, $po);
		$rs = $GLOBALS['db']->query($sqlc);
		if(!$rs) return array();
		$numRows = $rs->fetchColumn();
		$cInfo = array('count'=>$numRows, 'time'=>time());
		$_SESSION['sqlCountInfo'][$sk] = $cInfo;
	}
	if($numRows == 0) {
		$pageinfo['pagecount'] = 0;
		$pageinfo['count'] = 0;
		$pageinfo['page'] = 1;
		$pageinfo['pagesize'] = $pagesize;
		return array();
	}

	$pagecount = ceil($numRows / $pagesize);
	if($page == -1) $page = $pagecount;
	$pageinfo['pagecount'] = $pagecount;
	$pageinfo['count'] = $numRows;
	$pageinfo['page'] = $page;
	$pageinfo['pagesize'] = $pagesize;

	$start = ($page-1) * $pagesize;
	$end = $start + $pagesize;
	$sql = substr(trim($sql), 7);
	$sql = "select *
	from (
		select row_number() over(order by __tc__)__rn__,*
		from (select top {$end} 0 __tc__,{$sql})t
	)tt
	where __rn__>{$start}";
	//die($sql);
	$rs = $GLOBALS['db']->query($sql);
	if($rs === false) return array();
	return $rs->fetchAll(PDO::FETCH_ASSOC);
}
function gpageHTML($page, $pagecount, $total, $url, $N = 5)
{
	if( $pagecount == 0) return '';
	$page = intval($page);
	$html = "";
	
	if($url == '') {
		$qs = $_SERVER['QUERY_STRING'];
		//$qs = "act=listsp&listtype=1&s_text=&rduser=&page=";
		$qs = preg_replace("/page=(\d+)?\&?/", "", $qs);
		if(substr($qs, 0, 1) == '&') $qs = substr($qs, 1);
		if(substr($qs, strlen($qs)-1) == '&') $qs = substr($qs, 0, strlen($qs)-1);
		if($qs == '') $url = "?page=%s";
		else $url = "?{$qs}&page=%s";
		
	}
	$n = floor(($N - 1) / 2);
	$pos1 = $page - $n;
	$pos2 = $page + $n;
	if($N % 2 == 0) $pos2++;
	if($pos1 <= 0) {
		$pos2 += abs($pos1) + 1;
		$pos1 = 1;
	}
	if($pos2 > $pagecount) {
		$pos1 -= ($pos2 - $pagecount);
	}
	if($page != 1 && $pos1 > 1)
		$html .= '<a class="page2" href="' . str_replace("%s", strval($page - 1), $url) . '">上一页</a> <a href="' . str_replace("%s", strval(1), $url) . '" class="page2">1</a><span> ... </span>';
	for($i = $pos1; $i <= $pos2; $i++) {
		if($i >= 1 && $i <= $pagecount) {
			if($page == $i) {
				$html .= ' <a class="page1">' . $i . '</a>';
			} else {
				$html .= '<a class="page2" href="' . str_replace("%s", strval($i), $url) . '">' . $i . '</a>';
			}
		}
	}
	
	if($page != $pagecount) {
		$html .= '<span> . . . </span><a class="page2" href="' . str_replace("%s", strval($pagecount), $url) . '">'.$pagecount.'</a> <a class="page2" href="' . str_replace("%s", strval($page + 1), $url) . '">下一页</a>';
	}
	$html .= "<span>{$page}/{$pagecount}页    共{$total}条记录</span>";
	return $html;
}
function gbk2utf8($data) {
	if(is_array($data)) {
		foreach($data as $key => $item) {
			if(is_string($key)) {
				unset($data[$key]);
				$key = iconv('gbk','utf-8',$key);
			}
			$data[$key] = gbk2utf8($item);
		}
		return $data;
	}
	return iconv('gbk','utf-8',$data);
}

function gurl_par($par, $url = '')
{
	if($url == '') $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	$pos = strpos($url, '?');
	if($pos === false)
	{
		$url .= '?'.$par;
	}
	else
	{
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($par, $pars);
		foreach($pars as $k=>$v)
		{
			$querystring = g_url_par($k, $v, $querystring);
		}
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}

function g_url_par($var, $value, $querystring)
{
	if($querystring)
	{
		$pattern = "/([&]?)(".preg_quote($var)."\=)([^&]*)([&]?)/";
		$querystring = preg_match($pattern, $querystring) ? preg_replace($pattern, '${1}${2}'.$value.'${4}', $querystring) : $querystring."&$var=$value";
	}
	else
	{
		$querystring = $var.'='.$value;
	}
	return $querystring;
}

if(!function_exists("getip")) {
function getip()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	return $onlineip;
}
}
function gselectmenu($resouce,$selectname,$optionname,$optionvalue,$selectindex,$jsfunction="") {
	$returnstr = "<select name='{$selectname}' onchange='{$jsfunction}'>";
	//$returnstr.= "<option value='-9999'>?????</option>";

	foreach($resouce as $key=>$value) {
		if($optionname=="value") {	
			$selected = (strcmp($key,$selectindex)==0)?"selected":"";
			$returnstr.= "<option value='{$key}'  {$selected}>{$value}</option>";
		} else {
			$selected = (strcmp($value,$selectindex)==0)?"selected":"";
			$returnstr.= "<option value='{$value}'  {$selected}>{$key}</option>";
		}
	}

	$returnstr.= "</select>".chr(10).chr(13);
	
	return $returnstr;
}


function galert($msg, $location = '', $fyzm = '')
{
	if($location) $l = "location.href='{$location}';";
	else if($location===0) $l = "window.close();";
	else {
		$l = "history.back();";
		if($fyzm) $l.="$('yzmimg').src=$('yzmimg').src;";
	}
	$msg = str_replace('"','\\"', $msg);
	$html = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("'.$msg.'");'.$l.'</script>';
	echo $html;
	exit;
}

function gredirect($url)
{
	@header("Location: " . $url);
	echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
	exit;
}

function gstr_cut($str, $len, $c = "..", &$iscut = false, &$cutstr = '')
{
	$l = mb_strlen($str, 'utf-8');
	$iscut = false;
	if($l > $len) {
		$iscut = true;
		$cutstr = mb_substr($str, $len - 1, $l-$len+1, 'utf-8');
		$str = mb_substr($str, 0, $len-1, 'utf-8') . $c;
		
	}
	return $str;
}
function toHTML($str)
{
	$str = preg_replace("/^( |??)*(.+)/m", "????$2", trim(strip_tags($str)));
	$str = str_replace("\n", "<br />", $str);
	return $str;
}

function cookie($name, $value, $time = 0)
{
	$host = $_SERVER['HTTP_HOST'];
	$a = explode(".", $host);
	$a = array_slice($a, count($a) - 2);
	$domain = "." . implode(".", $a);

	@setcookie($name, $value, $time, "/", $domain);
}

function gdownload($path, $fn = '', $type = 1)
{
	if(substr($path, 0, 7) == 'http://') {
		
		header("Location: " . $path);
		return true;
	}

	if($type == 1 && !is_file($path)) return false;
	if($type == 2) {
		$filename = $fn;
	} else {
		if(!strstr($path, ".")) $ext = "data";
		else {
			$a = explode(".", $path);
			$ext = strtolower($a[count($a) - 1]);
		}
		set_time_limit(600);
		if($fn) $filename = urlencode($fn . "." . $ext);
		else $filename = urlencode(basename($path));
	}
	header("Cache-Control: public, must-revalidate");
	header("Pragma: hack");
	$mm = "application/octet-stream";
	header("Content-Type: " . $mm);
	header("Content-Length: " . ($type==2?strlen($path):filesize($path)));
	header("Content-Disposition: attachment; filename={$filename}");
	header("Content-Transfer-Encoding: binary");
	header("Connection: close");
	if($type == 2) {
		echo $path;
	} else {
		$f = fopen($path, "rb");
		if(!$f) return false;
		while($s = fread($f, 8192)) {
			echo $s;
			unset($s);
		}
		fclose($f);
	}
	return true;
}
class GYHJSON {
	static $isconv = -1;
    public static function encode($var, $_isconv = 0){
		if(self::$isconv == -1) self::$isconv = $_isconv;
        switch (gettype($var)){
            case 'boolean':
                return $var ? 'true' : 'false';

            case 'NULL':
                return 'null';

            case 'integer':
                return (int) $var;

            case 'double':
            case 'float':
                return (float) $var;

            case 'string':
				if(self::$isconv == 1) $var = iconv("gbk", "utf-8", $var);
                return '"' . preg_replace(array("/(?<=([".chr(0x81)."-".chr(0xff)."][".chr(0x40)."-".chr(0xff)."])|[".chr(0x1)."-".chr(0x7e)."]|^)\\\/", "|\"|", "|\n|", "|".chr(0x8)."|", "|\r|", "|\t|", "|[".chr(0x1)."-".chr(0x1f)."]|e"), array('\\\\\\', '\"', '\n', '\b', '\r', '\t', "'\u00' . bin2hex('$0')"), $var)  . '"';

            case 'array':
                if (is_array($var) && count($var) && (array_keys($var) !== range(0, count($var) - 1))) {
                    $prop= array_map(array("self", "_name_value"), array_keys($var), array_values($var));
                    return '{' . join(',', $prop) . '}';
                }
                $element = array_map(array("self", "encode"), $var);
                return '[' . join(',', $element) . ']';

            case 'object':
                $vars = get_object_vars($var);
                $prop= array_map(array("self", '_name_value'), array_keys($vars), array_values($vars));
                return '{' . join(',', $prop) . '}';
        }
    }

    private static function _name_value($name, $value){
        return self::encode(strval($name)) . ':' . self::encode($value);
    }
}
function gjson($obj, $p = 1)
{
	if(!$obj) $s = "[]";
	//else if($_GET['jsongbk']) $s = GYHJSON::encode($obj);
	else $s = json_encode(gbk2utf8($obj));
	
	if($_GET['compress'] == 1) $s = gzencode($s, 5);
	if($p) echo $s;
	else return $s;
}
function getArrList($data, $key)
{
	$arr = array();
	foreach($data as $item) {
		$arr[] = $item[$key];
	}
	return $arr;
}
function read_headers($hs) {
	$header = array();
	$a = explode("\n", $hs);
	foreach($a as $line) {
		$line = trim($line);
		if($line == '') continue;
		$pos = strpos($line, ":");
		if($pos === false) continue;
		$k = trim(substr($line, 0, $pos));
		$v = trim(substr($line, $pos + 1));
		$header[$k] = $v;
	}
	return $header;
}
function gquery($url, $post = array(), $header = array(), $config = array(), &$rs = array())
{
	global $cookiejar, $gquery_timeout;
	if(!$post) $post = array();if(!$header) $header = array();if(!$config) $config = array();

	$keep_alive = $config['keep_alive'];
	$curl_key = 'curl_'.substr(md5(find_str($url, '//', '/')), 0, 10);
	$curl = $GLOBALS[$curl_key];

	if($keep_alive && $curl) {
		$c = $curl;
		curl_setopt($c, CURLOPT_URL, $url);
	} else {
		$c = curl_init($url);
	}

	if(!$config['output']) {
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	} else {
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 0);
	}
	if($config['datafunc']) {
		curl_setopt($c, CURLOPT_WRITEFUNCTION, $config['datafunc']);
	}

	$cookiejar2 = '';

	if($config['cookie_file']) $cookiejar2 = $config['cookie_file'];
	else if($cookiejar) $cookiejar2 = $cookiejar;
	
	if(!$cookiejar2) {
		if(defined("COOKIEJAR")) $cookiejar2 = COOKIEJAR;
	}
	if($cookiejar2) {
		curl_setopt($c, CURLOPT_COOKIEJAR, $cookiejar2);
		curl_setopt($c, CURLOPT_COOKIEFILE, $cookiejar2);
	}
	
	if(!$config['no_follow']) {
		curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
	} else {
		curl_setopt($c, CURLOPT_FOLLOWLOCATION, 0);
	}
	curl_setopt($c, CURLOPT_AUTOREFERER, 1);

	if($config['get_header']) {
		curl_setopt($c, CURLOPT_HEADER, 1);
		curl_setopt($c, CURLINFO_HEADER_OUT, true);
	} else {
		curl_setopt($c, CURLOPT_HEADER, 0);
		curl_setopt($c, CURLINFO_HEADER_OUT, false);
	}

	if($config['timeout']) {
		$timeout = $config['timeout'];
	} else {
		$timeout = $gquery_timeout?$gquery_timeout:30;
	}
	curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 5);
	if($timeout < 1) {
		curl_setopt($c, CURLOPT_TIMEOUT_MS, intval($timeout*1000));
	} else {
		curl_setopt($c, CURLOPT_TIMEOUT, $timeout);
	}
	
	curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0); 
	if($config['host']) {
		curl_setopt($c, CURLOPT_PROXYTYPE, defined('CURLPROXY_SOCKS5_HOSTNAME')?CURLPROXY_SOCKS5_HOSTNAME:CURLPROXY_SOCKS5);  
		curl_setopt($c, CURLOPT_PROXY, $config['host']);  
		curl_setopt($c, CURLOPT_PROXYUSERPWD, $config['un'].":".$config['pw']);
	}

	$ua = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36';
	if(!$header) {
		$header = array($ua);
	}
	$has = false;
	foreach($header as $k => $v) {
		if(stristr($v, "user-agent")) {
			$has = true;
		}
		if($v == 'json') {
			$header[$k] = 'Content-Type: application/json;charset=UTF-8';
		}
	}
	if(!$has) $header[] = $ua;

	if($post) {
		if(is_array($post)) {
			if($config['posttype'] == 1) {
				$poststr = '';
				foreach($post as $k => $v) {
					$k = preg_replace("/#\d+#/", '', $k);
					if($poststr != '') $poststr .= "&";
					$poststr .= urlencode($k)."=".urlencode($v);
				}
			} else if($config['posttype'] == 2) {
				$boundary = "---------------------------".md5(microtime().rand());
				$poststr = '';
				foreach($post as $k => $v) {
					$k = preg_replace("/#\d+#/", '', $k);
					if(is_array($v) && $v['file_data']) { //文件
						$file_name = $v['file_name'];
						$file_type = $v['file_type'];
						if(!$file_type) $file_type = 'application/octet-stream';
						$fs = $v['file_data'];
						$poststr .= "--".$boundary . "\r\n"."Content-Disposition: form-data; name=\"".htmlspecialchars($k)."\"; filename=\"".htmlspecialchars($file_name)."\""
										."\r\nContent-Type: ".$file_type
										."\r\nContent-Length: ".strlen($fs)
										."\r\n\r\n".$fs."\r\n";
					} else {
						$poststr .= "--".$boundary . "\r\n"."Content-Disposition: form-data; name=\"".htmlspecialchars($k)."\""."\r\n\r\n".$v."\r\n";
					}
				}

				$poststr .= "--".$boundary . "--\r\n";
				if(!$header) $header = array();
				$header[] = "Content-Type: multipart/form-data; boundary=".$boundary;
				$header[] = "Content-Length: ".strlen($poststr);
			} else {
				$poststr = $post;
			}
		} else {
			$poststr = $post;
		}
		curl_setopt($c, CURLOPT_POST, 1);
		if($poststr === 'p') $poststr = '';
		curl_setopt($c, CURLOPT_POSTFIELDS, $poststr);
	}
	curl_setopt($c, CURLOPT_HTTPHEADER, $header);
	curl_setopt($c, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
	if($config['more_opts']) {
		foreach($config['more_opts'] as $k => $v) {
			curl_setopt($c, $k, $v);
		}
	}
	$t1 = microtime(1);
	$content = curl_exec($c);
	$t2 = microtime(1);
	$info = curl_getinfo($c);
	$err_info = curl_error($c);
	$rs['resonse_info'] = $info;
	$rs['err_info'] = $err_info;

	if($config['get_header']) {
		$header_size = $info['header_size'];
		if(!$header_size) {
			@curl_close($c);
			return false;
		}
		$hs = substr($content, 0, $header_size);
		$content = substr($content, $header_size);

		$rs['request_header'] = read_headers($info['request_header']);
		$rs['resonse_header'] = read_headers($hs);
		$rs['resonse_header_r'] = $hs;
	}
	if($keep_alive) {
		if($content !== false) {
			$GLOBALS[$curl_key] = $c;
		} else {
			$GLOBALS[$curl_key] = '';
		}
		
	} else {
		curl_close($c);
	}
	
	$log_func = $GLOBALS['gquery_log_func'];
	if($log_func) {
		$log_func(array(
			'url' => $url, 'poststr' => $poststr, 'content' => $content, 'time' => ($t2-$t1), 'header' => $header, 'rs' => $rs,
		));
	}
	return $content;
}

function isPhone($num)
{
	if(preg_match("/^1\d{10}$/", $num)) {
		if(!strstr($num, "0000000"))
			return true;
	}
	return false;
}

function dealChnUrl($s) {
	$a = explode("/", $s);
	$end = end($a);
	if(strstr($end, "?")) return $s;
	return substr($s, 0, strlen($s)-strlen($end)).urlencode(urldecode($end));
}

function ggetCutStr($content, $len)
{
	$s = gstr_cut($content, $len, '', $iscut, $cutstr);
	$s = htmlspecialchars($s);
	if($iscut) {
		$n = intval($GLOBALS['ghidespanN']);
		$id = "ghidespan_" . $n;
		$GLOBALS['ghidespanN'] = $n + 1;
		$s = '<span id="'.$id.'_c">'.$s.'</span>';
		$s .= '<span id="'.$id.'_dot">..</span>';
		$s .= '<span style="display:none" id="'.$id.'">'.$cutstr.'</span>';
		$s .= ' <a href="javascript:;" onClick="document.getElementById(\''.$id.'\').style.display=\'\';document.getElementById(\''.$id.'_dot\').style.display=\'none\';this.style.display=\'none\'" style="color:#0066ff;text-decoration:underline">???</a>';
	}
	return $s;
}

function isdx($num)
{
	$pre = substr($num, 0, 3);
	if($pre == '133' || $pre == '189' || $pre == '153' || $pre == '180' || $pre == '181' || $pre == '177') {
		return true;
	}
	return false;
}

function getlxdh($s)
{
	$lxdh = '';
	preg_match("/(^|[^\d])((189|133|153|180|181)\d{8})($|[^\d])/", $s, $m);
	$lxdh = $m[2];
	if(!$lxdh) {
		preg_match("/(^|[^\d])(1\d{10})($|[^\d])/", $s, $m);
		$lxdh = $m[2];
	}
	if(!$lxdh) {
		preg_match("/(^|[^\d])(\d{8})($|[^\d])/", $s, $m);
		$lxdh = $m[2];
	}
	return $lxdh;
}
function u2g($str)
{
	return iconv("utf-8", "gbk//IGNORE", $str);
}
function u2ga($arr)
{
	if(is_array($arr)) {
		foreach($arr as $key => $val) {
			$arr[$key] = u2ga($val);
		}
	} else {
		if(is_numeric($arr)) {
			return $arr;
		} else {
			return u2g($arr);
		}
	}
	return $arr;
}
function g2u($str)
{
	return iconv("gbk", "utf-8//IGNORE", $str);
}
function g2ua($arr)
{
	if(is_array($arr)) {
		foreach($arr as $key => $val) {
			$arr[$key] = g2ua($val);
		}
	} else {
		if(is_numeric($arr)) {
			return $arr;
		} else {
			return g2u($arr);
		}
	}
	return $arr;
}
function gto34($num)
{
	$s = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
	$l = strlen($s);
	$a1 = intval(bcdiv($num, $l));
	$a2 = bcmod($num, $l);
	$ss = '';
	while($a1 > 0) {
		$ss .= $s{$a2};
		$num = $a1;
		$a1 = intval(bcdiv($num, $l));
		$a2 = bcmod($num, $l);
	}
	$ss .= $s{$a2};
	return $ss;
}
function gfr34($ss)
{
	$s = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
	$N = 1;
	$total = 0;
	for($i = 0; $i < strlen($ss); $i++) {
		$a = $ss{$i};
		$p = strpos($s, $a);
		if($p === false) return "";
		$total = bcadd($total, bcmul($p, $N));
		$N = bcmul($N, strlen($s));
	}
	return $total;
}

/**
 * ?????????
 * @param $vStr
 * @return bool
 */
function isCreditNo($vStr)
{
    $vCity = array(
        '11','12','13','14','15','21','22',
        '23','31','32','33','34','35','36',
        '37','41','42','43','44','45','46',
        '50','51','52','53','54','61','62',
        '63','64','65','71','81','82','91'
    );
	if(strlen($vStr) != 18) return false;
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;

    if (!in_array(substr($vStr, 0, 2), $vCity)) return false;

    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);

	if ($vLength != 18) return false;

    if ($vLength == 18)
    {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }

    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18)
    {
        $vSum = 0;

        for ($i = 17 ; $i >= 0 ; $i--)
        {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
        }

        if($vSum % 11 != 1) return false;
    }

    return true;
}

function getqrimg($str)
{
	require_once dirname(__FILE__).'/qrcode/qrlib.php';
	$d = date("Ym");
		
	$t = "qr".time().rand().".png";
	QRcode::png($str, $t, 'L',9 , 6);
	$s = file_get_contents($t);
	@unlink($t);
	return $s;
}
function convarr($arr) {
	$arr2 = array();
	foreach($arr as $v) {
		$arr2[$v] = $v;
	}
	return $arr2;
}
function qs_replace($key, $v, $qs = '') {
	if(!$qs) $qs = $_SERVER['QUERY_STRING'];
	$a = explode("&", $qs);
	$qs2 = '';
	foreach($a as $item) {
		if($item == '') continue;
		$a2 = explode("=", $item);
		if($qs2 != '') $qs2 .= "&";
		if(count($a2) == 2) {
			if($a2[0] == $key) continue;
			$qs2 .= $a2[0]."=".$a2[1];
		} else {
			$qs2 .= $item;
		}
	}
	if($qs2 != '') $qs2 .= "&";
	$qs2 .= $key."=".$v;
	return $qs2;
}
function is_jdpw($pw) {
	if(strlen($pw) < 6) return true;
	if(preg_match("/^\d+$/", $pw)) return true;
	if(strstr($pw, "123456")) return true;
	return false;
}
function getSizeStr($size) {
	$arr = array('byte', 'KB', 'MB', 'G');
	if($size <= 1024) return '1KB';
	$n = 0;
	while($size > 1024) {
		$size = $size/1024;
		$n++;
	}
	$size = rtrim(rtrim(number_format($size, 2, '.', ''), '0'), '.');
	return $size."".$arr[$n];
}
function echoRs($status, $message, $data = array(), $return = 0) {
	global $rs, $echoRs_gzip;
	$info = array(
		'status' => $status,
		'message' => $message
	);
	if($GLOBALS['echoRsAddUser'] && !$data['user'] && $status > 0) $data['user'] = $GLOBALS['user'];
	if($data) $info['data'] = $data;
	if($return == 1) return $info;

	header("Content-Type: application/json;charset=UTF-8");
	if(defined("JSON_UNESCAPED_UNICODE")) $rs = json_encode($info, JSON_UNESCAPED_UNICODE);
	else $rs = json_encode($info);
	if($return == 2) return $rs;

	if($GLOBALS['request_aes_key']) {
		$rs = aes_encrypt($rs, $GLOBALS['request_aes_key']);
	} else {
		if($_GET['gyhdebug']) {
			print_r($info);
			exit;
		}
	}
	if($echoRs_gzip) ob_start("ob_gzhandler");
	echo $rs;
	if($echoRs_gzip) ob_end_flush();
	if(function_exists("page_close")) {
		page_close();
	}
	exit;
}
function arr_skey($arr) {
	$arr2 = array();
	foreach($arr as $value) {
		if($value == '请选择') $arr2[''] = $value;
		else $arr2[$value] = $value;
	}
	return $arr2;
}
function data2kv($data, $zd1, $zd2, $addall = false) {
	$arr2 = array();
	if($addall) {
		if(is_string($addall)) $arr2[''] = $addall;
		else $arr2[''] = '请选择';
	}
	foreach($data as $item) {
		if($zd2 == '#item#') {
			$arr2[$item[$zd1]] = $item;
		} else{
			if(isset($arr2[$item[$zd1]])) $arr2[$item[$zd1]] .= "#$#".$item[$zd2];
			else $arr2[$item[$zd1]] = $item[$zd2];
		}
	}
	return $arr2;
}
function data2kv_info($list1, $list2, $zd1, $zd2, $zd3, $zd4) {
	$info = array();
	foreach($list1 as $item1) {
		$id1 = $item1[$zd1];
		$arr = array();
		foreach($list2 as $item2) { if($item2[$zd2] == $id1) $arr[] = $item2;}
		$info[$id1] = data2kv($arr, $zd3, $zd4);
	}
	return $info;
}
function getQRCode($str) {
	require_once 'qrcode/qrlib.php';
	$fn = time()."_".rand();
	QRcode::png($str, $fn,'40',40,0);

	//header("Content-Type: image/png");
	$s = file_get_contents($fn);
	@unlink($fn);
	return $s;
}

function list_has($s1, $s2, $split = ',') {
	if(strstr($split.$s1.$split, $split.$s2.$split)) {
		return true;
	}
	return false;
}

function time_str($t = 0) {
	if(!$t) $t = time();
	return date("Y-m-d H:i:s", $t);
}


if(!function_exists("pe")) {
function pe($a, $isexit = 1) {
	print_r($a);
	if($isexit) exit;
}
}

function pe1($a, $isexit = 1) {
	print_r($a);
	if($isexit) exit;
}
if(!function_exists("ve")) {
function ve($a, $isexit = 1) {
	var_dump($a);
	if($isexit) exit;
}
}

function ve1($a, $isexit = 1) {
	var_dump($a);
	if($isexit) exit;
}

function aes_encrypt($orig_data, $key, $iv = '', $raw = false) {
	$mode = MCRYPT_MODE_CBC;
	if($iv == 'ecb') {
		$iv = str_repeat("0", 16);
		$mode = MCRYPT_MODE_ECB;
	}
	$encrypter = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
	
	$blocksize = mcrypt_enc_get_block_size($encrypter);
	$padding = $blocksize - strlen($orig_data) % $blocksize;
	$padding_text = str_repeat(chr($padding), $padding);
	$orig_data .= $padding_text;
	

	if(!$iv) $iv = substr($key, 0, 16);
	mcrypt_generic_init($encrypter, $key, $iv);
	$ciphertext = mcrypt_generic($encrypter, $orig_data);
	mcrypt_generic_deinit($encrypter);
	mcrypt_module_close($encrypter);
	if(!$raw) $ciphertext =  base64_encode($ciphertext);
	return $ciphertext;
}

function aes_decrypt($ciphertext, $key, $iv = '', $raw = false) {
	if($ciphertext == '') return false;
	$mode = MCRYPT_MODE_CBC;
	if($iv == 'ecb') {
		$iv = str_repeat("0", 16);
		$mode = MCRYPT_MODE_ECB;
	}

	$encrypter = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
	if(!$raw) $ciphertext = base64_decode($ciphertext);

	if(!$iv) $iv = substr($key, 0, 16);
	mcrypt_generic_init($encrypter, $key, $iv);
	$orig_data = mdecrypt_generic($encrypter, $ciphertext);
	mcrypt_generic_deinit($encrypter);
	mcrypt_module_close($encrypter);
	$length = strlen($orig_data);
	$unpadding = ord($orig_data[$length - 1]);
	return substr($orig_data, 0, $length - $unpadding);
}
function rsa_pubkey_convert($mod, $exp) {
	if(!class_exists("Zeal_Security_RSAPublicKey")) {
	class Zeal_Security_RSAPublicKey   
	{   
		/**  
		 * ASN.1 type INTEGER class  
		 */   
		const ASN_TYPE_INTEGER = 0x02;   
	   
		/**  
		 * ASN.1 type BIT STRING class  
		 */   
		const ASN_TYPE_BITSTRING = 0x03;   
	   
		/**  
		 * ASN.1 type SEQUENCE class  
		 */   
		const ASN_TYPE_SEQUENCE = 0x30;   
	   
		/**  
		 * The Identifier for RSA Keys  
		 */   
		const RSA_KEY_IDENTIFIER = '300D06092A864886F70D0101010500';   
	   
		/**  
		 * Constructor  (disabled)  
		 *  
		 * @return void  
		 */   
		private function __construct()   
		{   
		}   
	   
		static function getPublicKeyFromModExp($modulus, $exponent)
		 {
			 $modulusInteger  = self::_encodeValue($modulus, self::ASN_TYPE_INTEGER);
			 $exponentInteger = self::_encodeValue($exponent, self::ASN_TYPE_INTEGER);
			 $modExpSequence  = self::_encodeValue($modulusInteger . $exponentInteger, self::ASN_TYPE_SEQUENCE);
			 $modExpBitString = self::_encodeValue($modExpSequence, self::ASN_TYPE_BITSTRING);
	 
			 $binRsaKeyIdentifier = pack( "H*", self::RSA_KEY_IDENTIFIER );
	 
			 $publicKeySequence = self::_encodeValue($binRsaKeyIdentifier . $modExpBitString, self::ASN_TYPE_SEQUENCE);
	 
			 $publicKeyInfoBase64 = base64_encode( $publicKeySequence );
	 
			 $publicKeyString = "-----BEGIN PUBLIC KEY-----\n";
			 $publicKeyString .= wordwrap($publicKeyInfoBase64, 64, "\n", true);
			 $publicKeyString .= "\n-----END PUBLIC KEY-----\n";
	 
			 return $publicKeyString;
		 }
	 
		 static function _encodeValue($data, $type)
		 {
			 // Null pad some data when we get it (integer values > 128 and bitstrings)
			 if( (($type == self::ASN_TYPE_INTEGER) && (ord($data) > 0x7f)) ||
				 ($type == self::ASN_TYPE_BITSTRING)) {
					 $data = "\0$data";
			 }
	 
			 $len = strlen($data);
	 
			 // encode the value based on length of the string
			 // I'm fairly confident that this is by no means a complete implementation
			 // but it is enough for our purposes
			 switch(true) {
				 case ($len < 128):
					 return sprintf("%c%c%s", $type, $len, $data);
				 case ($len < 0x0100):
					 return sprintf("%c%c%c%s", $type, 0x81, $len, $data);
				 case ($len < 0x010000):
					 return sprintf("%c%c%c%c%s", $type, 0x82, $len / 0x0100, $len % 0x0100, $data);
				 default:
					 require_once 'Zend/InfoCard/Xml/Security/Exception.php';
					 throw new Zend_InfoCard_Xml_Security_Exception("Could not encode value");
			 }
	 
			 require_once 'Zend/InfoCard/Xml/Security/Exception.php';
			 throw new Zend_InfoCard_Xml_Security_Exception("Invalid code path");
		 }
	} }

	$s = Zeal_Security_RSAPublicKey::getPublicKeyFromModExp(hex2bin($mod), hex2bin($exp));
	return openssl_get_publickey($s);
}

function replace_first($f, $r, $s, $is_i = false) {
	if($is_i) $pos = stripos($s, $f);
	else $pos = strpos($s, $f);
	if($pos === false) return $s;
	return substr($s, 0, $pos).$r.substr($s, $pos+strlen($f));
}
function set_star($s, $n, $type = 1) { //1右边 2中间
	$len = mb_strlen($s, 'UTF-8');
	if($type == 1) {
		return mb_substr($s, 0, $len - $n).str_repeat("*", $n);
	} else if($type == 2) {
		$len1 = ceil(($len - $n)/2);
		return mb_substr($s, 0, $len1).str_repeat("*", $n).mb_substr($s, $len1+$n);
	}
}
function fg($fn) {
	return file_get_contents($fn);
}
function fp($fn, $s, $append = false) {
	if($append) file_put_contents($fn, $s, FILE_APPEND);
	else file_put_contents($fn, $s);
}
function je($a) {
	return json_encode($a, JSON_UNESCAPED_UNICODE);
}
function jd($s) {
	return json_decode($s, true, 512 , JSON_BIGINT_AS_STRING);
}
function de($r) {
	ini_set("display_errors", $r?"on":"off");
}
function read_xml($xstr) {
	$parser = xml_parser_create('UTF-8');
	xml_parse_into_struct($parser, '<greadxml>'.$xstr.'</greadxml>', $vals, $index);
	xml_parser_free($parser);
	$arr = array();
	$nowPath = '';
	$countInfo = array();
	$valueInfo = array();

	foreach($vals as $item) {
		$tag = $item['tag'];
		$type = $item['type'];
		$level = $item['level'];
		$attributes = $item['attributes'];
		$value = $item['value'];

		if($type == 'cdata' && trim($value) == '') continue;
		//print_r($item);

		if($type == 'open') {
			if($nowPath != '') $nowPath .= "/";
			$nowPath .= $tag;

			if(isset($countInfo[$nowPath])) $countInfo[$nowPath]++;
			else $countInfo[$nowPath] = 0;

			$a1 = explode("/", $nowPath);
			array_pop($a1);
			$nowPath1 = implode("/", $a1);

			$n1 = intval($countInfo[$nowPath1]);
			//if(!trim($value)) $valueInfo[$nowPath] = array('', $n1, count($arr[$nowPath][$n1]));
			//else {
			//	unset($valueInfo[$nowPath]);
			//}
			$valueInfo[$nowPath] = array(trim($value), $n1, intval(@count($arr[$nowPath][$n1])));

			$arr[$nowPath][$n1][] = array(
				'attributes' => $attributes,
				'value' => $value,
			);
		} else if($type == 'close') {
			//echo 'close:'.$tag."-".$nowPath."\n";
			if(isset($valueInfo[$nowPath])) {
				//print_r($valueInfo[$nowPath]);exit;
				$va = $valueInfo[$nowPath];
				$arr[$nowPath][$va[1]][$va[2]]['value'] = $va[0];
				$arr[$nowPath][$va[1]][$va[2]]['more_attributes'] = $va[3];
			}

			$a = explode("/", $nowPath);
			array_pop($a);
			$nowPath = implode("/", $a);
			
			//echo 'count:'.$nowPath."++\n";
			//$countInfo[$nowPath]++;
			
		} else if($type == 'complete') {
			if($nowPath != '') $nowPath .= "/";
			$nowPath .= $tag;

			//echo $nowPath."\t".intval($countInfo[$nowPath])."\t".$nowPath."\n";
			$a1 = explode("/", $nowPath);
			array_pop($a1);

			if($tag == 'BR' && $value == '') $value = "\n";
			$nowPath2 = '';
			foreach($a1 as $n1 => $tag1) {
				if($nowPath2 != '') $nowPath2 .= "/";
				$nowPath2 .= $tag1;
				if($n1 >= 1 && isset($valueInfo[$nowPath2])) {
					$valueInfo[$nowPath2][0] .= $value;
					if($attributes) $valueInfo[$nowPath2][3][substr($nowPath, strlen($nowPath2)+1)][] = $attributes;
				}
			}

			$nowPath1 = implode("/", $a1);
			
			$arr[$nowPath][intval($countInfo[$nowPath1])][] = array(
				'attributes' => $attributes,
				'value' => $value,
			);
			
			$a = explode("/", $nowPath);
			array_pop($a);
			$nowPath = implode("/", $a);

		} else if($type == 'cdata') {
			//print_r(array_keys($valueInfo));exit;
			$valueInfo[$nowPath][0] .= $value;
		}
		//echo $nowPath."\n";
	}
	$arr2 = array();
	foreach($arr as $key => $item) {
		if($key == 'GREADXML') continue;
		$key = substr($key, 9);
		$arr2[$key] = $item;
	}
	return $arr2;
}

function saveUploadFile($type, $fInfo, $rootpath = '', $allowExts = '') { //$type 1 FILE 2 base64
	if(!$rootpath) $rootpath = 'upload/';
	if(!$allowExts) $allowExts = 'jpg|jpeg|png';
	if(substr($rootpath, -1) != '/') $rootpath .= '/';
	if($type == 1) {
		if(!$_FILES[$fInfo] || !$_FILES[$fInfo]['size']) return false;
		$fn = $_FILES[$fInfo]['name'];
		$fpath = $_FILES[$fInfo]['tmp_name'];
		$fsize = $_FILES[$fInfo]['size'];
		
		$a = explode(".", $fn);
		if(count($a) < 2) {
			return false;
		}
		$ext = strtolower($a[count($a) - 1]);
		$allowExtsArr = explode("|", $allowExts);
		if(!in_array($ext, $allowExtsArr)) {
			return false;
		}
		if(in_array($ext, array('jpg', 'jpeg', 'png', 'gif', 'bmp')) && !@imagecreatefromstring(file_get_contents($fpath))) {
			return false;
		}
		
	} else if($type == 2) {
		$picdata = stripslashes($fInfo);
		$ext = '';
		if(strpos($picdata, 'data:image/jpeg;base64,') === 0) { $ext = 'jpg'; $pos = 23;}
		else if(strpos($picdata, 'data:image/png;base64,') === 0) { $ext = 'png'; $pos = 22;}
		else return false;
		$picdata = substr($picdata, $pos);
		$picdata = base64_decode($picdata);
		if(!$picdata) return false;
		if(!@imagecreatefromstring($picdata)) {
			return false;
		}
		$fsize = strlen($picdata);
	} else {
		return false;
	}

	if(!is_dir($rootpath)) @mkdir($rootpath);
	$d = date("Ymd");
	$dir = $rootpath."{$d}";
	if(!is_dir($dir)) mkdir($dir);
	$path = $dir."/".md5(time()."_".rand()).".".$ext;
	if($type == 2) file_put_contents($path, $picdata);
	else copy($fpath, $path);
	if(file_exists($path) && filesize($path) == $fsize) {
		return $path;
	} else {
		return false;
	}
}

function find_str($s, $start, $end = '', $is_i = false, $is_contain = false, &$last_pos = 0) {
	$func = 'strpos';
	if($is_i) $func = 'stripos';

	if($start !== '') {
		$pos1 = $func($s, $start);
		if($pos1 === false) return false;
	} else {
		$pos1 = 0;
	}
	$slen = strlen($start);
	if($end !== '') {
		$pos2 = $func($s, $end, $pos1+$slen);
		if($pos2 === false) return false;
	} else {
		$pos2 = strlen($s);
	}
	if($is_contain) {
		$last_pos = $pos1 + ($pos2-$pos1+strlen($end));
		return substr($s, $pos1, $pos2-$pos1+strlen($end));
	} else {
		$last_pos = $pos1+$slen + ($pos2-$pos1-$slen);
		return substr($s, $pos1+$slen, $pos2-$pos1-$slen);
	}
}
function arr_part($arr, $keys, $split = ',') {
	$a = explode($split, $keys);
	$arr2 = array();
	foreach($a as $key) {
		$arr2[$key] = $arr[$key];
	}
	return $arr2;
}

function str_json($s) {
	$s1 = je(array($s.""));
	return substr($s1, 2, -2);
}

function star_eq($s, $star_s, $star = '*') {
	if($star_s === '*') return true;
	if($s === $star_s) return true;
	while(strstr($star_s, $star.$star)) $star_s = str_replace($star.$star, $star, $star_s);
	$sa = explode($star, $star_s);
	if(count($sa) != 2) return false;
	if($sa[1] === '') {
		if(strpos($s, $sa[0]) === 0) return true;
		return false;
	}
	if($sa[0] === '') {
		if(strrpos($s, $sa[1]) === strlen($s) - strlen($sa[1])) return true;
		return false;
	}
	if(strpos($s, $sa[0]) === 0 && (count($sa) == 2 && strrpos($s, $sa[1]) === strlen($s) - strlen($sa[1]))) {
		return true;
	}
	return false;
}
function ds($t = '') {
	if($t) return date("Y-m-d H:i:s", $t);
	return date("Y-m-d H:i:s");
}
function ukey() {
	return md5(microtime()."_".rand());
}


function backup_mysql($port, $dbnames, $target, $config = array())
{
	global $root, $t, $ftpList;
	if(!$t) $t = date("YmdHis");

	$host = '127.0.0.1';
	$a = explode(":", $port);
	if(count($a) == 2) {
		$host = $a[0];
		$port = $a[1];
	}

	$pre = $config['pre'];
	$un = $config['un']; if(!$un) $un = 'root';
	$pw = $config['pw']; if(!$pw) $pw = '123';
	$ignore = $config['ignore'];
	$ignoreDB = $config['ignoreDB'];
	$no_ssl = $config['no_ssl'];

	if($pre) $pre = '_'.$pre;
	$sqlgzfn = $t."{$pre}_sql.zip";

	$db = mysql_connect("{$host}:{$port}", $un, $pw);
	mysql_query("set names utf8", $db);

	if($dbnames == '*') {
		$ignoreDBList = array();
		if($ignoreDB) $ignoreDBList = explode(",", $ignoreDB);
		$rs = mysql_query("show databases", $db);
		$a = array();
		while($row = mysql_fetch_array($rs)) {
			$dbname = $row['Database'];
			if($dbname == 'information_schema' || $dbname == 'mysql' || $dbname == 'performance_schema' || $dbname == 'test' || $dbname == 'sys') continue;
			if(in_array($dbname, $ignoreDBList)) continue;
			$a[] = $dbname;
		}
		if(!$a) return ;
		$dbnames = implode(" ", $a);
	}

	$a = explode(" ", $dbnames);
	$fna = array();
	foreach($a as $dbname) {
		mysql_select_db($dbname, $db);
		$sqlfn = $dbname."_".$t.".sql";
		$fna[] = $sqlfn;
		$sqlfn2 = $root.$sqlfn;
		@unlink($sqlfn2);
		$ignoreCMD = '';

		$moreCreateSQL = '';
		if($ignore) {
			$a2 = explode(",", $ignore);
			$a2 = array_unique($a2);
			foreach($a2 as $ignoreTable) {
				$ignoreCMD .= " --ignore-table={$dbname}.".$ignoreTable;

				$rs2 = mysql_query("show create table `{$ignoreTable}`", $db);
				if(!$rs2) {
					echo $dbname.":".$ignoreTable." no\n";
					continue;
				}

				$row2 = mysql_fetch_array($rs2);
				if(!$row2) {
					echo $dbname.":".$ignoreTable." no\n";
					continue;
				}
				$createSQL = $row2['Create Table'];
				$createSQL = preg_replace("/ AUTO_INCREMENT=\d+/", "", $createSQL);
				$moreCreateSQL .= "\n".$createSQL.";\n\n";
				

			}
		}
		$mysql_path = "/usr/local/mysql";
		if($config['mysql_path']) $mysql_path = $config['mysql_path'];

		$row1 = fetchOne("show master status", $db);

		$cmd = $mysql_path."/bin/mysqldump -h{$host} -P{$port} -u{$un} -p{$pw} --force -R --skip-lock-tables".($no_ssl?" --ssl-mode=DISABLED":"")." {$dbname}{$ignoreCMD} > " . $sqlfn2;
		exec($cmd);

		file_put_contents($sqlfn2, $moreCreateSQL, FILE_APPEND);
		file_put_contents($sqlfn2, "\n-- ".$row1['File'].": ".$row1['Position'], FILE_APPEND);
	}
	mysql_close($db);
	
	$s = implode(" ", $fna);
	$cmd = "cd {$root}\nzip -q {$sqlgzfn} {$s}";
	exec($cmd);
	foreach($fna as $fn) {
		$sqlfn2 = $root.$fn;
		unlink($sqlfn2);
	}
	foreach($ftpList as $ftpInfo) {
		if($ftpInfo[0] == 'gsend') {
			$url = $ftpInfo[1];
			$enkey = $ftpInfo[2];

			gsend_do_send_file($enkey, $target, $root.$sqlgzfn, $url);
		} else {
			$r = false;
			for($i = 1; $i <= 3; $i++) {
				$r = ftpput($ftpInfo, $root.$sqlgzfn, '', $target);
				if($r) break;
			}
		}
	}
	unlink($root.$sqlgzfn);
}
function backup_web($path, $target, $pre, $config = array())
{
	global $root, $t, $ftpList;
	if(!$t) $t = date("YmdHis");

	$noexts = array();
	$musts = array();
	$excludes = array();
	$imcludes = array();

	if($config['noexts']) { $noexts = $config['noexts']; if(!is_array($noexts)) $noexts = explode(',', $noexts); $noexts = array_unique($noexts); }
	if($config['musts']) { $musts = $config['musts']; if(!is_array($musts)) $musts = explode(',', $musts); $musts = array_unique($musts); }
	if($config['excludes']) { $excludes = $config['excludes']; if(!is_array($excludes)) $excludes = explode(',', $excludes); $excludes = array_unique($excludes); }
	if($config['imcludes']) { $imcludes = $config['imcludes']; if(!is_array($imcludes)) $imcludes = explode(',', $imcludes); $imcludes = array_unique($imcludes); }


	$a = explode("/", $path);
	$dirname = $a[count($a) - 1];
	$pathname = substr($path, 0, -strlen($dirname));
	$ftfn = $root.$t."_{$pre}.zip";


	$ex = '';
	foreach($excludes as $exclude) {
		if($exclude[0] == '/') $exclude = $dirname.$exclude;
		if(!strstr($exclude, '*')) $exclude .= '*';
		$ex .= ' '.str_replace('*', '\\*', $exclude);
	}
	foreach($noexts as $ext) {
		$ex .= ' \\*.'.$ext.'';
		$ex .= ' \\*.'.strtoupper($ext).'';
	}
	if($ex) $ex = " -x".$ex;

	$ix = '';
	foreach($imcludes as $imclude) {
		if($imclude[0] == '/') $imclude = $dirname.$imclude;
		if(!strstr($imclude, '*')) $imclude .= '*';
		$ix .= ' '.str_replace('*', '\\*', $imclude);
	}
	if($ix) $ix = " -i".$ix;

	$rc = ' -r';
	if($config['no_r']) $rc = '';
	$cmd = "cd {$pathname}\nzip{$rc} -q -y {$ftfn} {$dirname} {$ex} {$ix}";

	exec($cmd);
	if($musts) {
		foreach($musts as $must) {
			if(!file_exists("{$pathname}{$dirname}/{$must}")) continue;
			$ex = '';
			foreach($excludes as $exclude) {
				if($exclude[0] == '/') $exclude = $dirname.$exclude;
				if(!strstr($exclude, '*')) $exclude .= '*';
				$ex .= ' '.str_replace('*', '\\*', $exclude);
			}
			if($ex) $ex = " -x".$ex;
			exec("cd {$pathname}\nzip{$rc} -q -y {$ftfn} {$dirname}/{$must} {$ex}");
		}
	}
	foreach($ftpList as $ftpInfo) {

		if($ftpInfo[0] == 'gsend') {
			$url = $ftpInfo[1];
			$enkey = $ftpInfo[2];

			gsend_do_send_file($enkey, $target, $ftfn, $url);
		} else {
			$r = false;
			for($i = 1; $i <= 3; $i++) { 
				$r = ftpput($ftpInfo, $ftfn, '', $target);
				if($r) break;
			}
		}
	}
	unlink($ftfn);
}
function backup_crontab($target)
{
	global $root, $t, $ftpList;
	if(!$t) $t = date("YmdHis");
	ob_start();
	passthru("crontab -l");
	$cron = ob_get_clean();
	$cronfn = "{$t}_cron.txt";
	file_put_contents($root.$cronfn, $cron);
	foreach($ftpList as $ftpInfo) {

		if($ftpInfo[0] == 'gsend') {
			$url = $ftpInfo[1];
			$enkey = $ftpInfo[2];

			gsend_do_send_file($enkey, $target, $root.$cronfn, $url);
		} else {
			$r = false;
			for($i = 1; $i <= 3; $i++) {
				$r = ftpput($ftpInfo, $root.$cronfn, '', $target);
				if($r) break;
			}
		}
	}

	unlink($root.$cronfn);
}
function ftpput($ftpInfo, $filename, $target = '', $dir = '')
{
	$conn = @ftp_connect($ftpInfo[0], $ftpInfo[1], 5);
	if(!$conn) return false;
	@ftp_login($conn, $ftpInfo[2], $ftpInfo[3]);
	@ftp_pasv($conn, true);

	$r = @ftp_chdir($conn, $dir);
	if(!$r) {
		$a = explode("/", $dir);
		$nowdir = '';
		foreach($a as $dirname) {
			if($nowdir != '') $nowdir .= "/";
			$r = @ftp_chdir($conn, $dirname);
			if(!$r) {
				ftp_mkdir($conn, $dirname);
				$r = @ftp_chdir($conn, $dirname);
				if(!$r) return false;
			}
		}
	}

	//$dirlist = ftp_nlist($conn, ".");
	//var_dump($dirlist);
	$file = fopen($filename, "r");
	if($target == '') $target = basename($filename);
	$res = @ftp_fput($conn, $target, $file, FTP_BINARY);
	@ftp_close($conn);
	fclose($file);
	if(!$res) return false;
	return true;
}

function backup_file($fn, $target)
{
	global $root, $t, $ftpList;
	if(!$t) $t = date("YmdHis");
	$tmpfn = "{$t}_".basename($fn);
	copy($fn, $root.$tmpfn);
	foreach($ftpList as $ftpInfo) {
		if($ftpInfo[0] == 'gsend') {
			$url = $ftpInfo[1];
			$enkey = $ftpInfo[2];

			gsend_do_send_file($enkey, $target, $root.$tmpfn, $url);
		} else {
			$r = false;
			for($i = 1; $i <= 3; $i++) {
				$r = ftpput($ftpInfo, $root.$tmpfn, '', $target);
				if($r) break;
			}
		}
	}

	unlink($root.$tmpfn);
}

function usort_func($a, $b) {
	global $usort_zd, $usort_type;
	$v1 = $a[$usort_zd]; $v2 = $b[$usort_zd];
	if($v1 === $v2) return 0;
	$t = 0;
	if($v1 > $v2) $t = 1;
	else if($v1 < $v2) $t = -1;
	if($usort_type == 2) $t = -$t;
	return $t;
}

function func_path($func) {
	if(!function_exists($func)) return false;
	$c = new ReflectionFunction($func);
	return $c->getFileName();
}

function get_ext($fn) {
	$a = explode(".", $fn);
	if(count($a) < 2) {
		return '';
	}
	$ext = strtolower($a[count($a) - 1]);
	return $ext;
}

function isInt($s) {
	$s = $s."";
	if(!is_numeric($s)) return false;
	$len = strlen($s);
	if($len >= 10) return false;
	if($len > 1 && substr($s, 0, 1) === '-') {
		$s = substr($s, 1);
		$len -= 1;
	}
	if(!preg_match("/^\d+$/", $s)) return false;

	if($len > 1 && $s[0] == '0') return false;

	return true;
}

function isFloat($s, $maxf = 5) {
	if(!$maxf) $maxf = 5;
	$s = $s."";
	if(!is_numeric($s)) return false;
	if(isInt($s)) return true;
	$a = explode(".", $s);
	if(count($a) != 2) return false;
	if(!isInt($a[0])) return false;
	if(!preg_match("/^\d+$/", $a[1])) return false;
	if(strlen($a[1]) > $maxf) return false;
	return true;
}

function oci_zy($s) {
	return str_replace("'", "''", $s);
}

function hasRole($roleid) {
	global $adminInfo;
	$roles = ",".$adminInfo['role'].",";
	if(strstr($roles, ",{$roleid},")) return true;
	return false;
}

function set_mem($s) {
	ini_set("memory_limit", $s);
}

function post_str($post) {
	$poststr = '';
	foreach($post as $key => $value) {
		$key = preg_replace("/#\d+#/", '', $key);
		if($poststr != '') $poststr .= "&";
		$poststr .= $key . "=" . urlencode($value);
	}
	return $poststr;
}

function qs2arr($s, $isurl = false) {
	if($isurl) {
		$pos1 = strpos($s, '?');
		if($pos1 !== false) {
			$s = substr($s, $pos1 + 1);
		}
	}
	$a1 = explode('&', $s);
	$info = array();
	foreach($a1 as $v1) {
		$a2 = explode('=', $v1);
		if(count($a2) != 2) continue;
		$info[urldecode($a2[0])] = urldecode($a2[1]);
	}
	return $info;
}
function arr2qs($a, $encode = false, $nokong = false) {
	$s = '';
	foreach($a as $k => $v) {
		if($nokong && ($v.'')==='') continue;
		if($s != '') $s .= '&';
		if($encode) $s .= urlencode($k)."=".urlencode($v);
		else $s .= $k."=".$v;
	}
	return $s;
}
function exec_lock($mpath) {
	$pos = strrpos($mpath, "/");
	$mfn = substr($mpath, $pos + 1);

	$mfn2 = substr($mfn, 0, -1);

	ob_start();
	passthru('ps -ef|grep "'.$mfn2.'"');
	$s = ob_get_clean();

	$a = explode("\n", $s);
	$total = 0;
	foreach($a as $line) {
		$line = trim($line);
		if($line == '') continue;
		if(strstr($line, '/bin/sh -c')) continue;
		$pos = strpos($line, $mfn);
		if($pos === false) continue;
		if($pos == strlen($line)- strlen($mfn)) {
			$total++;
		} else {
			$c = substr($line, $pos + strlen($mfn), 1);
			if($c == ' ' || $c == "\t") {
				$total++;
			}
		}
	}
	if($total > 1) {
		echo "lock err\n";
		exit;
	}
}

function exec_lock_sock($key) {
	global $lock_sock;
	$ks = '';
	while(1) {
		$ks .= preg_replace("/[a-z]/", '', md5($key));
		if(strlen($ks) >= 14) break;

		$key = md5($key);
	}
	$a = str_split($ks, 3);
	$ip1 = '127';
	$port1 = 0;
	for($i = 0; $i <= 3; $i++) {
		if($i == 3) {
			$port1 = intval(($a[3].$a[4])%55534+10000);
		} else {
			$ip1 .= ".".(intval($a[$i])%255);
		}
	}

	$lock_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	socket_set_nonblock($lock_sock);
	$r = @socket_bind($lock_sock, $ip1, $port1);
	if(!$r) {
		echo "lock err1\n";
		exit;
	}
	$r = @socket_listen($lock_sock, 1);
	if(!$r) {
		echo "lock err2\n";
		exit;
	}
}

function resizeImg($fn, $pictype, $maxsize, &$retwidth, &$retheight) {
	if($pictype == 1) {
		$pics = fg($fn);
	} else {
		$pics = $fn;
	}
	$img = imagecreatefromstring($pics);
	if(!$img) return false;
	
	$width = imagesx($img);
	$height = imagesy($img);

	if($width <= $maxsize && $height <= $maxsize) {
		$retwidth = $width;
		$retheight = $height;
		imagedestroy($img);
		return $pics;
	}


	if($width >= $height) {
		$height2 = $maxsize;
		$width2 = ceil($width*$height2/$height);
	} else {
		$width2 = $maxsize;
		$height2 = ceil($height*$width2/$width);
	}
	$retwidth = $width2;
	$retheight = $height2;
	$img2 = imagecreatetruecolor($width2, $height2);
	imagecopyresized($img2, $img, 0, 0, 0, 0, $width2, $height2, $width, $height);
	ob_start();
	imagejpeg($img2, null, 90);
	$s = ob_get_clean();
	imagedestroy($img);
	imagedestroy($img2);

	return $s;
}
function get_day_list($start_day, $end_day) {
	$list = array();

	if(strlen($start_day.'') == 10) {
		while($start_day <= $end_day) {
			$list[] = $start_day;
			$start_day = date('Y-m-d', strtotime("{$start_day} +1 day"));
		}
	} else {
		for($i = $start_day; $i <= $end_day; $i++) {
			if($i < 0) $op = '';
			else $op = '+';
			$list[] = date('Y-m-d', strtotime("{$op}{$i} day"));
		}
	}

	
	return $list;
}
function clear_html_zs($s) {
	while(1) {
		$pos1 = strpos($s, "<!--");
		if($pos1 === false) break;

		$pos2 = strpos($s, "-->", $pos1 + 4);
		if($pos2 === false) break;

		$s = substr($s, 0, $pos1) . substr($s, $pos2 + 3);
	}
	return $s;
}
function clear_html_tag($s, $tag) {
	while(1) {
		$pos1 = strpos($s, "<{$tag}>");
		if($pos1 === false) $pos1 = strpos($s, "<{$tag} ");
		if($pos1 === false) break;

		$pos2 = strpos($s, "</{$tag}>", $pos1 + 1);
		if($pos2 === false) break;

		$s = substr($s, 0, $pos1) . substr($s, $pos2 + strlen($tag)+3);
	}
	return $s;
}
function get_file_list($dn, $vn = 0) {
	global $t_file_list, $t_file_rootlen;
	if($vn == 0) {
		$t_file_list = array();
		$t_file_rootlen = strlen($dn);
	}
	$dir = opendir($dn);
	while($fn = readdir($dir)) {
		if($fn == '.' || $fn == '..') continue;
		$path2 = $dn."/".$fn;
		if(is_dir($path2)) {
			get_file_list($path2, $vn + 1);
		} else {
			$t_file_list[] = array(substr($path2, $t_file_rootlen + 1), filesize($path2));
		}
	}
	closedir($dir);
	if($vn == 0) {
		return $t_file_list;
	}
}

function gsend_request($enkey, $url, $info, $more_data = '') {
	$host = '';
	$a1 = explode("##", $url);
	if(count($a1) == 2) {
		$url = $a1[0];
		$host = $a1[1];
	}
	$header = array('Content-Type: application/octet-stream');
	if($host) $header[] = 'Host: '.$host;

	$jsone = aes_encrypt(je($info), $enkey);
	$psl = pack('L', strlen($jsone));

	$s1 = gquery($url, $psl.$jsone.$more_data, $header);
	return aes_decrypt($s1, $enkey);
}

function gsend_deal_recv_file($enkey, $root, $no_get = false) {
	$ps = fg("php://input");
	$pslen = strlen($ps);

	$psl = substr($ps, 0, 4);
	$a = unpack('L', $psl);
	$jslen = $a[1];

	$jsone = substr($ps, 4, $jslen);
	$json = aes_decrypt($jsone, $enkey);
	$info = jd($json);


	$path = $info['path'];
	$fn = $info['fn'];
	$size = $info['size'];
	$first = $info['first'];
	$last = $info['last'];
	$nowPos = $info['nowPos'];
	$act = $info['act'];

	if($act == 'get_file_list' && !$no_get) {
		$list = get_file_list($root);
		echo aes_encrypt(je($list), $enkey);
		exit;
	}
	if($act == 'del_file_list' && !$no_get) {
		$file_list = $info['file_list'];
		if(!$file_list) exit;

		foreach($file_list as $fn) {
			if(strstr($fn, '..')) exit;
			$path = $root."/".$fn;
			@unlink($path);
		}

		echo aes_encrypt('ok', $enkey);
		exit;
	}

	if(!$path || !$fn || !$size || ($nowPos.'') === '') exit;
	if(strstr($path, '..')) exit;

	$path = $root."/".$path;
	if(!is_dir($path)) mkdir($path, 0700, true);
	if(!is_dir($path)) exit;

	$path2 = $path."/".$fn;
	$path2_tmp = $path2.".tmp";
	if($first) {
		if(is_file($path2_tmp)) @unlink($path2_tmp);
		if(is_file($path2)) @unlink($path2);
	}
	$s = '';
	$suc = false;
	if($pslen == (4+$jslen+$size+4)) {
		if(substr($ps, 4+$jslen, 2) == 'st' && substr($ps, 4+$jslen+$size+2, 2) == 'ed') {
			$s = substr($ps, 4+$jslen+2, $size);
			$suc = true;
		}
	}
	if(!$suc) {
		exit;
	}
	$fp = fopen($path2_tmp, "c+b");
	fseek($fp, intval($nowPos), SEEK_SET);
	fwrite($fp, $s);
	fclose($fp);

	if($last) {
		if(is_file($path2)) {
			@unlink($path2);
		}
		rename($path2_tmp, $path2);
	}
	echo aes_encrypt('ok', $enkey);
}

function gsend_do_send_file($enkey, $dest_path, $fn, $url, $fn_new = '') {
	$per = 2000000;

	$fsize = filesize($fn);
	$n = ceil($fsize/$per);
	if(!$fn_new) $fn_new = basename($fn);

	$list = array();
	for($i = 0; $i < $n; $i++) {
		$len = $per;
		if($i == $n - 1) {
			$len = $fsize % $per;
			if($len == 0) $len = $per;
		}
		$list[] = array($i*$per, $len);
	}

	$fp = fopen($fn, "rb");
	if(!$fp) exit;

	$count = count($list);
	$nowPos = 0;
	foreach($list as $n => $item) {
		list($start, $len) = $item;
		//echo $n."/".$count."\n";

		$slen = $len;
		$s = '';
		while($slen > 0) {
			$s1 = fread($fp, $slen);
			$s .= $s1;
			$slen -= strlen($s1);
		}

		$info = array('path' => $dest_path, 'fn' => $fn_new, 'size' => $len, 'nowPos' => $nowPos);
		if($n == 0) $info['first'] = 1;
		if($n == $count - 1) $info['last'] = 1;

		$suc = false;
		for($try = 1; $try <= 100; $try++) {
			$s1 = gsend_request($enkey, $url, $info, "st".$s."ed");
			if($s1 == 'ok') {
				$suc = true;
				break;
			}
			sleep(3);
		}
		if(!$suc) return false;
		$nowPos += $len;
		
	}
	return true;
}
function arr_del($arr, $zd, $v) {
	$arr2 = array();
	foreach($arr as $item) {
		if(is_array($v)) {
			$has = false;
			foreach($v as $v1) {
				if($item[$zd].'' === $v1.'') {
					$has = true;
					break;
				}
			}
			if(!$has) {
				$arr2[] = $item;
			}
		} else {
			if($item[$zd].'' === $v.'') {
			} else {
				$arr2[] = $item;
			}
		}
	}
	return $arr2;
}
function arr_add($arr, $after_zd, $after_v, $add_v, $is_arr = false) {
	$arr2 = array();
	$has_add = false;
	foreach($arr as $item) {
		$arr2[] = $item;
		if(!$has_add && $item[$after_zd].'' === $after_v.'') {
			if($is_arr) {
				foreach($add_v as $item2) {
					$arr2[] = $item2;
				}
			} else {
				$arr2[] = $add_v;
			}
			
			$has_add = true;
		}
	}
	return $arr2;
}
function arr_find_n($arr, $zd, $v) {
	foreach($arr as $n => $item) {
		if($item[$zd].'' === $v.'') {
			return $n;
		}
	}
	return -1;
}

function isImage($s){
	if(bin2hex(substr($s, 0, 4)) == '89504e47') return true; //png
	if(bin2hex(substr($s, 0, 3)) == 'ffd8ff') return true; //jpg
	if(substr($s, 0, 2) == 'BM' && bin2hex(substr($s, 6, 4)) == '00000000') return true; //bmp
	if(substr($s, 0, 3) == 'GIF') return true; //gif
	return false;
}

function posSplit($f, $str){
	$pos = strpos($str, $f);
	if($pos === false) return false;
	$arr = array();
	$arr[0] = substr($str, 0, $pos);
	$arr[1] = substr($str, $pos + strlen($f));
	return $arr;
}
function readexcel($filePath, $sheet_name = '') {
	if(!class_exists("gyh\\GyhReadsheet\\IOFactory")) {
		require_once(dirname(__FILE__).'/gyhReadsheet/xlsx.php');
	}
	try {
		$zmArr1 = array();
		$zmArr2 = array();
		$characters = range('A', 'Z');
		for($i = 1; $i <= 500; $i++) {
			$result = '';
			$num = $i;
			while ($num > 0) {
				$num--;
				$remainder = $num % 26;
				$result = $characters[$remainder] . $result;
				$num = (int)($num / 26);
			}
			$zmArr1[$i] = $result;
			$zmArr2[$result] = $i;
		}

		$spreadsheet = gyh\GyhReadsheet\IOFactory::load($filePath);

		if(!$sheet_name) {
			$sheet = $spreadsheet->getSheet(0);
		} else {
			$sheetNames = $spreadsheet->getSheetNames();
			if($sheet_name == 'getSheetNames') {
				return $sheetNames;
			}
			foreach($sheetNames as $n => $name1) {
				if(trim($name1) === trim($sheet_name)) {
					$sheet = $spreadsheet->getSheet($n);
				}
			}
			if(!$sheet) return array();
		}
		$mergeCells = $sheet->getMergeCells();
		$mergeValues = array();
		$mergeValuesStr = array();
		foreach ($mergeCells as $mergeCellRange) {
			list($startCell, $endCell) = explode(':', $mergeCellRange);
			if(!preg_match("/([A-Z]+)(\d+)/", $startCell, $m1)) continue;
			if(!preg_match("/([A-Z]+)(\d+)/", $endCell, $m2)) continue;
			$zm1 = $m1[1]; $num1 = $m1[2];
			$zm2 = $m2[1]; $num2 = $m2[2];

			$cellValue = $sheet->getCell($startCell)->getValue();
			$mergeValuesStr[] = $cellValue.'';

			//echo $startCell.":".$endCell."\n";
			$zm1N = $zmArr2[$zm1]; $zm2N = $zmArr2[$zm2];
			for($i = $zm1N; $i <= $zm2N; $i++) {
				for($j = $num1; $j <= $num2; $j++) {
					$cn = $zmArr1[$i].$j;
					$mergeValues[$cn] = count($mergeValuesStr)-1;
				}
			}
		}


		$list = array();
		// 遍历行和列读取数据
		
		$n1 = -1;
		foreach ($sheet->getRowIterator() as $row) {
			$n1++;
			$cellIterator = $row->getCellIterator();
			$cellIterator->setIterateOnlyExistingCells(false);
			$arr = array();
			$n2 = -1;
			foreach ($cellIterator as $cell) {
				$n2++;
				// 获取单元格的数据并输出
				$value = $cell->getValue().'';
				$cn = $cell->getCoordinate();
				if(isset($mergeValues[$cn])) {
					$value = $mergeValuesStr[$mergeValues[$cn]];
				}
				if($n1 > 0 && $value && is_numeric($value)) {
					$value1 = intval($value);
					if($value1 >= 40000 && $value1 <= 50000) { //日期
						$t1 = $list[0][$n2];
						if(strstr($t1, '日期') || strstr($t1, '时间') || strstr($t1, '时刻')) {
							if(strpos($value, '.') !== false) {
								$a1 = explode(".", $value);
								$value = date("Y-m-d H:i:s", 86400*(intval($a1[0])-25569)+(round(floatval("0.".$a1[1])*86400)-28800));
							} else {
								$value = date("Y-m-d", 86400*($value1-25569));
							}
							
						}
					} else if(substr_count($value, '.') === 1) {
						$value1 = floatval($value);
						if($value1 > 0 && $value1 < 1) { //日期
							$t1 = $list[0][$n2];
							if(strstr($t1, '时间') || strstr($t1, '时刻')) {
								$n = 86400*$value1;
								$value = str_pad(floor($n/3600).'', 2, '0', STR_PAD_LEFT).":".str_pad(round(($n%3600)/60).'', 2, '0', STR_PAD_LEFT);
							}
						}
					}
				}
				$arr[] = $value;
			}
			$list[] = $arr;
		}
		$count = count($list);
		$hasKong = false;
		for($i = $count - 1; $i >= 0; $i--) {
			$s = trim(implode('', $list[$i]));
			if($s !== '') break;
			$hasKong = true;
		}
		if($hasKong) {
			$list = array_slice($list, 0, $i+1);
		}
		$colKong = array();
		foreach($list as $item) {
			if(!$colKong) {
				foreach($item as $n => $v) {
					$colKong[$n] = 1;
				}
			}
			foreach($item as $n => $v) {
				if($colKong[$n] == 0) continue;
				if(($v.'') !== '') {
					$colKong[$n] = 0;
				}
			}
		}
		$kongInfo = array();
		foreach($colKong as $n => $v) {
			if($v == 1) {
				$kongInfo[$n] = 1;
			}
		}

		if($kongInfo) {
			$list2 = array();
			foreach($list as $item) {
				$item2 = array();
				foreach($item as $n => $v) {
					if($kongInfo[$n] == 1) continue;
					$item2[] = $v;
				}
				$list2[] = $item2;
			}
			$list = $list2;
		}

		return $list;
	} catch(Exception $e) {
		
		return array();
	} catch(Error $e) {
		print_r($e);
		return array();
	}
}

if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle) {
        return $needle !== '' && strpos($haystack, $needle) !== false;
    }
}
if (!function_exists('str_starts_with')) {
    function str_starts_with($string, $prefix) {
        return strpos($string, $prefix) === 0;
    }
}
if (!function_exists('str_ends_with')) {
    function str_ends_with($string, $suffix) {
        $length = strlen($suffix);
        if ($length === 0) {
            return true;
        }
        return (substr($string, -$length) === $suffix);
    }
}
function num_per($v, $len = 2) {
	return num_format(floatval($v)*100, $len).'%';
}
function num_format($v, $len = 2) {
	$s = number_format(floatval($v), $len, '.', '');
	$s = rtrim($s, '0');
	$s = rtrim($s, '.');
	return $s;
}
function generateShade($hex, $percent) {
    $hex = str_replace('#', '', $hex);
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // 计算变暗或变亮
    $r = round($r * (1 - $percent/100));
    $g = round($g * (1 - $percent/100));
    $b = round($b * (1 - $percent/100));
    
    // 确保值在0-255范围内
    $r = max(0, min(255, $r));
    $g = max(0, min(255, $g));
    $b = max(0, min(255, $b));
    
    return sprintf("#%02x%02x%02x", $r, $g, $b);
}
function toMonth($n, $format = 'Ym') {
	return date($format, strtotime($n.' month', strtotime(date('Y-m-01'))));
}